package com.panda.utils;


/*
    提取对变量的监听

    格式为

    #([变量名称列表])->{

            需要执行的代码

    }



    转变之后的结果是

    $scope.$watch("[变量列表]",function()体);

 */

import com.google.common.base.Joiner;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class WatchUtils {



    private static final Pattern pattern = Pattern.compile("(?<=[;\n])[\n ]*#(deep)?[ \n]*\\(([^()]+)\\)[\n ]*->[\n ]*");

    static String transform(String s) {


        if ("".equals(s)) {
            return s;
        }

        Matcher matcher = pattern.matcher(s);

        char[] chars = s.toCharArray();

        String b = s;

        while (matcher.find()) {

            int end = Finder.findBody(chars, matcher.end());

            String body = s.substring(matcher.end(), end).trim();

            String w = s.substring(matcher.start(), end);

            if ("".equals(body.trim())) {
                System.err.println("警告:");
                System.err.println(w);
                System.err.println("没有体!");
            } else {


                //剔除掉被监听属性的 $scope. 前缀
                String attr = matcher.group(2).replace("$scope.", "");

                String[] split = attr.split(",");

                attr = Joiner.on("+").join(split);

                String to;

                if (matcher.group(1) == null) {
                    to = "\n$scope.$watch(\"" + attr + "\",function()" + body + ");\n";
                } else {
                    to = "\n$scope.$watch(\"" + attr + "\",function()" + body + ",true);\n";
                }

                b = b.replace(w, to);

            }


        }

        return b;

    }


}

